package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private DatagramSocket socket;

    //保存服务器的源IP 和 源端口号
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        //客户端不用指定端口号，由用户的操作系统自行决定其端口号
        socket = new DatagramSocket();
    }

    //客户端启动
    public void start() throws IOException {
        System.out.println("客户端已启动...");
        Scanner scan = new Scanner(System.in);
        while(true) {
            //用户输入数据
            System.out.println("请输入你要发送的数据：");
            if(!scan.hasNext()) {
                break;
            }

            String request = scan.nextLine();

            //构建请求数据报,传入目的IP和目的端口
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);

            //发送数据报
            socket.send(requestPacket);

            //接收响应的数据报
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("响应：%s\n",response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
